"""
ECS实体工厂 - 创建游戏实体
"""
from ecs.components import Transform, Renderable, Physics, Health, PlayerControl, Weapon, AI
from ecs.entity import Entity
import pygame
import random

def create_player(world, player_id: int, x: float, y: float, sprite_path: str, controls: dict, screen_size: tuple) -> Entity:
    """
    创建玩家实体
    Args:
        world: 游戏世界实例
        x: 初始X坐标
        y: 初始Y坐标
        sprite_path: 精灵图路径
        controls: 控制键映射
        screen_size: 屏幕尺寸 (宽, 高)
    """
    player = world.add_entity(Entity())
    
    # 加载精灵图
    sprite = pygame.image.load(sprite_path).convert_alpha()
    
    # 添加组件
    player.add_component(Transform(x=x, y=y))
    player.add_component(Renderable(sprite=sprite, layer=1))
    player.add_component(Physics(velocity_x=0, velocity_y=0, 
                                collider=pygame.Rect(x, y, sprite.get_width(), sprite.get_height())))
    player.add_component(Health(current=20, max=20))
    player.add_component(PlayerControl(
        up_key=controls['up'],
        down_key=controls['down'],
        left_key=controls['left'],
        right_key=controls['right'],
        fire_key=controls.get('fire', pygame.K_SPACE),
        speed=5.0
    ))
    
    return player

def create_weapon(world, owner_id: int, x: float, y: float, sprite_path: str) -> Entity:
    """
    创建武器实体
    Args:
        world: 游戏世界实例
        owner_id: 拥有者实体ID
        x: 初始X坐标
        y: 初始Y坐标
        sprite_path: 武器精灵图路径
    """
    weapon = world.add_entity(Entity())
    sprite = pygame.image.load(sprite_path).convert_alpha()
    
    weapon.add_component(Transform(x=x, y=y))
    weapon.add_component(Renderable(sprite=sprite, layer=2))
    weapon.add_component(Weapon(
        damage=1,
        cooldown=0.5,
        projectile_speed=10.0,
        owner_id=owner_id
    ))
    
    return weapon

def create_hamster(world, sprite_path: str, screen_size: tuple) -> Entity:
    """
    创建仓鼠实体
    Args:
        world: 游戏世界实例
        sprite_path: 精灵图路径
        screen_size: 屏幕尺寸 (宽, 高)
    """
    hamster = world.add_entity(Entity())
    sprite = pygame.image.load(sprite_path).convert_alpha()
    width, height = sprite.get_size()
    
    # 随机初始位置
    x = random.randint(0, screen_size[0] - width)
    y = random.randint(0, screen_size[1] - height)
    
    hamster.add_component(Transform(x=x, y=y))
    hamster.add_component(Renderable(sprite=sprite, layer=0))
    hamster.add_component(AI(behavior_type="wander"))
    
    return hamster